package com.heima.big_event03.Interceptor;

import com.heima.big_event03.utils.JwtUtil;
import com.heima.big_event03.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 生成一个拦截器
 * 下一步：到com.heima.config.WebMvcConfiguration注册拦截器
 */
@Component
@Slf4j
public class myIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //校验规则
        String token = request.getHeader("Authorization");
        log.info("开始校验jwt.token{}",token);
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //最好拿token到redis比对一下判断是否过期
            //每次访问页面都把token解析到ThreadLocal中
            ThreadLocalUtil.set(claims);
            log.info("往ThreadLocalUtils存储用户信息");
        } catch (Exception e) {
            response.setStatus(401);
            //不放行
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求完成后清除数据，防止内存泄露
        ThreadLocalUtil.remove();
    }
}
